package com.lumiclass.myapplication3.view

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import android.view.View

class MyView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
    private val mTag = javaClass.simpleName

    @SuppressLint("DrawAllocation")
    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        Log.d("MyView", "measuredWidth: $measuredWidth, measuredHeight: $measuredHeight")
        val r = measuredWidth / 2f
        val circleX = left + r
        val circleY = top + measuredHeight / 2
        val paint = Paint()
        paint.color = Color.BLACK
        canvas.drawCircle(circleX, circleY * 1f, r, paint)
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        //父View的宽、高
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        val width = getMySize(100, widthMeasureSpec)
        val height = getMySize(200, heightMeasureSpec)
        setMeasuredDimension(width, height)
    }

    /**
     * 获取View最终宽、高
     */
    private fun getMySize(defSize: Int, measureSpec: Int): Int {
        var realSize = 0
        val mode = MeasureSpec.getMode(measureSpec)
        val size = MeasureSpec.getSize(defSize)

        when (mode) {
            MeasureSpec.AT_MOST -> {
                Log.d("MyView", "mode: at_most, size: $size")
                //wrap
                realSize = size
            }
            MeasureSpec.EXACTLY -> {
                //match_parent
                realSize = defSize
                Log.d("MyView", "mode: exactly, size: $size")
            }
            MeasureSpec.UNSPECIFIED -> {
                Log.d("MyView", "mode: unspecified, size: $size")
                realSize = defSize
            }
        }
        return realSize
    }

    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        Log.d(mTag, "dispatchTouchEvent")
        return super.dispatchTouchEvent(ev)
    }

    @SuppressLint("ClickableViewAccessibility")
    override fun onTouchEvent(event: MotionEvent?): Boolean {
        Log.d(mTag, "dispatchTouchEvent")
        return super.onTouchEvent(event)
    }


}